<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800003 extends BasePay{

    private $appSecret = '6884eb488c8c4aedad1d337c096eceac';
    private $appKey = '7970919';

    public function order()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
        parent::order();
        $params = Request::instance()->param();
        $json_string = file_get_contents(env('PLATFORM.USD'));
        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if(empty($usd)){
            mylog('计费点对应的美元金额找不到');
            return false;
        }
        // $payData = [
        //     "amount" => $usd['Mpay'],
        //     "countryCode" => $params['countryCode'],
        //     "currency" => 'USD',
        //     "orderId" => $this->order_array['id'].'G'.$this->order_array['amount'],
        //     "orderDescription" => $this->order_array['goods_name'],
        //     'memo'=>$this->order_array['id'].'G'.$this->order_array['amount']
        // ];
        // mylog(json_encode($payData));
        // $data = $this->aloneSignBody($payData);
        // mylog(json_encode($data));
        // $response = $this->curl('https://api.paynicorn.com/trade/v3/transaction/pay', $data);
        // var_dump($response);die;
        // $response = '{
        //     "responseCode": "000000",
        //     "responseMessage": "success",
        //     "content": "eyJjb2RlIjoiMDAwMCIsIm1lc3NhZ2UiOiJzdWNjZXNzIiwic3RhdHVzIjoiLTEiLCJ0eG5JZCI6IjEyMzAxMDIwMDAwMDAyMjQwIiwid2ViVXJsIjoiaHR0cHM6Ly9oNS12My5wYXluaWNvcm4uY29tL2Nhc2hpZXItdW5pdmVyc2FsLz90PTEyMzAxMDIwMDAwMDAyMjQwIiwicm5VcmwiOm51bGwsInBheUluc3RydWN0aW9uIjpudWxsLCJxdWlja1BheU1ldGhvZCI6bnVsbH0=",
        //     "sign": "d704adcbbc74c67f2f6d2f43b3cb30ee"
        // }';
        // $obj = $this->decodeResponse($response);
        $data_Arr = [
            'code'=>200,
            'msg'=>'success',
            // 'data'=>json_decode($obj['content'],true),
            'info'=>['stroeid'=>$this->order_array['goods_id'],'amount_usd'=>$usd['Mpay'],'amount_rmb'=>$this->order_array['amount'],'orderId'=>$this->order_array['id']]
        ];
        putsuccess($data_Arr);
    }

    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);

        try{
            //验证签名
            $sign = md5($params['content'].$this->appSecret);
            if($sign != $params['sign']){
                throw new \Exception('sign false');
            }
            $data = json_decode(base64_decode($params['content']),true);
            $orderInfo = json_decode($data['memo'],true);
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$orderInfo['orderId']])->find();
            if ($tradeLog){
                $tradeLog->transactionID = $data['txnId'];
                $tradeLog->dollPrice = $data['amount'];
                $tradeLog->dollPriceType = $data['currency'];
                $tradeLog->save();
            }
            //效验订单
            $notifyService = new NotifyService();
            $order_info = $notifyService->checkOrder($orderInfo["orderId"],$orderInfo["rmb_price"]);
            if($order_info == false){
                throw new \Exception('checkOrder false');
            }
            if ($order_info["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800003 订单已经处理过了 订单id".$order_info['id']);
                return "success_".$data['txnId'];
            }
            

            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            return "success_".$data['txnId'];
        }catch (\Exception $exception){
            mylog('800003-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return 'FAIL';
        }

    }

    
    /**
     * @param $data
     * @return array
     */
    protected function aloneSignBody($data)
    {
        $data['requestTime'] = $this->getMillisecond();
        $base64Content = base64_encode(json_encode($data));
        return [
            'appKey' => $this->appKey,
            'content' => $base64Content,
            'sign' => md5($base64Content . $this->appSecret),
        ];
    }

    /**
     * @param $msg
     * @return string[]
     */
    protected function errorResponse($msg)
    {
        return [
            'responseCode' => '10000',
            'responseMessage' => $msg,
            'content' => '',
        ];
    }

    /**
     * @param $body
     * @return bool|mixed|string[]
     */
    protected function decodeResponse($body)
    {
        $data = json_decode($body, true);

        if (!$data) {
            return $this->errorResponse('error response');
        }
        if ($data['responseCode'] != '000000') {
            $data = json_decode($data['responseMessage'], true);
        }
        $sign = md5($data['content'] . $this->appSecret);
        if ($data['sign'] == $sign) {
            $data['content'] = base64_decode($data['content']);
            return $data;
        }

        return false;
    }

    /**
     * @return float
     */
    protected function getMillisecond()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }


    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($body));
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        if ($error = curl_error($ch)) {
            mylog("800003error");
            mylog($error);
            die($error);
        }
        curl_close($ch);
        mylog($response);
        return $response;

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_FAILONERROR, false);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_POST, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        // $response = curl_exec($ch);
        // curl_close($ch);
        // return $response;
    }

   
}
